<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';

import { Button, Empty, message, Modal, Spin } from 'ant-design-vue';

import {
  deleteBusinessPositionExperience,
  getCurrentPositionExperiences,
} from '#/api/per/businessPositionExperience';
import QueryForm from '#/components/query-form/queryForm.vue';
import { useGridFormSchema } from '#/views/per/components/positionExperience/data';

import PositionExperienceEdit from '../../components/positionExperience/positionExperienceEdit.vue';
import PositionExperienceList from '../../components/positionExperience/positionExperienceList.vue';

const listData = ref<any[]>([]);
const loading = ref(false);

const editState = reactive({
  current: null as any,
  type: 'add' as 'add' | 'edit',
  visible: false,
});
const editRef = ref<any>(null);

const queryRef = ref<InstanceType<typeof QueryForm>>(null);

// 获取列表
async function fetchList() {
  loading.value = true;
  try {
    const params = await queryRef.value?.getValues();
    const res = await getCurrentPositionExperiences(params);
    listData.value = (res ?? []).sort(
      (a, b) => (b.endDate || 0) - (a.endDate || 0),
    );
  } catch (error) {
    console.error(error);
    message.error('获取任职经历失败');
  } finally {
    loading.value = false;
  }
}

// 删除
async function handleDelete(item: any) {
  Modal.confirm({
    title: '确认删除吗？',
    content: `确定要删除【${item.positionUnit}】这条任职经历吗？`,
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await deleteBusinessPositionExperience({ id: item.id });
        message.success('删除成功');
        fetchList();
      } catch (error) {
        console.error(error);
        message.error('删除失败');
      }
    },
  });
}

// 编辑弹窗
function openEdit(type: 'add' | 'edit', item?: any) {
  editState.type = type;
  editState.current = item ? { ...item } : null;
  editState.visible = true;
}

const handleAdd = () => openEdit('add');
const handleEdit = (item: any) => openEdit('edit', item);

// 保存
async function handleSave() {
  const ok = await editRef.value?.onConfirm();
  if (!ok) return;
  message.success('保存成功');
  editState.visible = false;
  fetchList();
}

onMounted(fetchList);
</script>

<template>
  <Page auto-content-height>
    <Spin :spinning="loading" tip="加载中...">
      <!-- 查询条件 -->
      <QueryForm
        ref="queryRef"
        :schema="useGridFormSchema()"
        @submit="fetchList"
        @reset="fetchList"
      >
        <!-- 新增按钮插到“查询按钮前面” -->
        <template #expand-before>
          <Button type="primary" @click="handleAdd">新增</Button>
        </template>
      </QueryForm>

      <!-- 无数据 -->
      <div v-if="listData.length === 0" class="empty-tip">
        <Card>
          <Empty description="暂无任职经历">
            <Button type="primary" @click="handleAdd">新增任职经历</Button>
          </Empty>
        </Card>
      </div>

      <!-- 查看的子组件 -->
      <PositionExperienceList
        :list-data="listData"
        @edit="handleEdit"
        @delete="handleDelete"
      />

      <!-- 修改的弹窗 -->
      <Modal
        v-model:visible="editState.visible"
        :title="editState.type === 'add' ? '新增任职经历' : '编辑任职经历'"
        width="60%"
        :body-style="{ maxHeight: '80vh', overflowY: 'auto' }"
        destroy-on-close
      >
        <PositionExperienceEdit ref="editRef" :data="editState.current" />

        <template #footer>
          <Button @click="editState.visible = false">取消</Button>
          <Button type="primary" @click="handleSave">保存</Button>
        </template>
      </Modal>
    </Spin>
  </Page>
</template>

<style scoped>
.empty-tip {
  padding: 20px;
  text-align: center;
  color: #999;
}
</style>
